package com.tegtech.core.controller;

import java.beans.PropertyEditorSupport;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.function.Supplier;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.tegtech.common.constant.ErrorMsg;
import com.tegtech.common.domain.Result;
import com.tegtech.common.utils.date.DateUtils;
import com.tegtech.common.utils.http.ServletUtils;
import com.tegtech.core.page.PageResult;
import com.tegtech.core.page.PageSupport;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * web层通用数据处理
 * 
 * @author Jun
 */
@Slf4j
public class BaseController {

	/**
	 * 将前台传递过来的日期格式的字符串，自动转化为Date类型
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		// Date 类型转换
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(DateUtils.parseDate(text));
			}
		});
	}
	
	/**
	 * 数据分页
	 * @param supplier
	 * @return
	 */
	protected PageResult buildPageResult(Supplier<List<?>> supplier) {
		PageSupport.startPage();
		return PageSupport.buildPageResult(supplier.get());
	}
	
	/**
	 * Excel导出, 通过浏览器下载的形式
	 * @param <T>
	 * @param fileName	文件名/标题名
	 * @param clazz		
	 * @param exportList
	 * @param exclusions	过滤的属性(列名)
	 */
	protected <T> void exportExcel(String fileName, Class<T> clazz, List<T> exportList, String ... exclusions) {
		// 生成excel文件
		ExportParams params = new ExportParams(fileName, "Sheet1");
		params.setExclusions(exclusions);
		try(Workbook workbook = ExcelExportUtil.exportExcel(params, clazz, exportList)) {
			// 设置响应头信息
			HttpServletResponse response = ServletUtils.getResponse();
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Data-Type", "file");
			response.setDateHeader("Expires", 0);
			response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf-8") + ".xls");
			// 写入Excel文件信息
			workbook.write(response.getOutputStream());
		} catch (Exception e) {
			log.error("excel export failed, detail : {}", e);
		} 
    }

	/**
	 * 设置浏览器缓存
	 * @param time	缓存时长，单位：秒
	 */
	protected void browserCache(long time) {
		ServletUtils.getResponse().setHeader("Cache-Control", "max-age=" + time);
	}

	/**
	 * 响应返回结果
	 * 
	 * @param rows 影响行数
	 * @return 操作结果
	 */
	protected Result toResult(int rows) {
		return rows > 0 ? Result.ok() : Result.err().msg(ErrorMsg.NO_MODIFIED);
	}

	/**
	 * 页面跳转
	 */
	public String redirect(String url) {
		return StrUtil.format("redirect:{}", url);
	}
}
